<?php
// application/api/controller/v1/Role.php

namespace app\api\controller;

use app\api\validate\RoleValidate;
use app\api\model\SystemRole;
use app\common\model\Help;
use think\Controller;
use think\exception\ValidateException;
use think\Request;
use think\Db;

class Role extends Controller
{
    protected $middleware = [];

    /**
     * 角色列表
     */
    public function index(Request $request)
    {
        try {
            $param = $request->param();
            if($param){
                $params = $param['params'];
            }else{
                $params = [];
            }

            $page = $params['page'] ?? 1;
            $size = $params['size'] ?? 10;

            $help = new Help();
            $system_user_id = $help->system_user();

            $roleModel = new SystemRole();
            $result = $roleModel->getRoleList($params, $page, $size,$system_user_id);

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 角色详情
     */
    public function read()
    {
        $id = input("id")??'';
        try {
            $roleModel = new SystemRole();
            $role = $roleModel->getRoleWithMenus($id);


            if (!$role) {
                return json([
                    'code' => 400,
                    'message' => '角色不存在'
                ], 400);
            }

            $role['custom_org_ids'] = explode(',',$role['custom_org_ids']);
            $role['customOrgIds'] = $role['custom_org_ids'];
            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $role
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 角色详情
     */
    public function read_find()
    {
        $id = input("id")??'';
        $system_user_id = input("system_user_id")??'';
        try {
            $roleModel = new SystemRole();
            $role = $roleModel->getRoleWithMenus($id,$system_user_id);

            if (!$role) {
                return json([
                    'code' => 400,
                    'message' => '角色不存在'
                ], 400);
            }

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $role
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 添加角色
     */
    public function save(Request $request)
    {
        try {
            $data = $request->param();

            // 验证数据
            $validate = new RoleValidate();
            if (!$validate->scene('add')->check($data)) {
                return json([
                    'code' => 400,
                    'message' => $validate->getError()
                ], 400);
            }

            $roleModel = new SystemRole();

            $have = Db::table("system_role")->where(['role_key'=>$data['role_key']])->find();
            if(!empty($have)){
                return json([
                    'code' => 400,
                    'message' => '角色标识已被其他人使用，请您更换一个哦！'
                ], 400);
            }



            $help = new Help();
            $data['system_user_id'] = $help->system_user();

            $roleId = $roleModel->addRole($data);

            $help = new Help();
            $help->system_log($data, '添加角色');

            return json([
                'code' => 200,
                'message' => '添加成功',
                'data' => ['id' => $roleId]
            ]);

        } catch (ValidateException $e) {
            return json([
                'code' => 400,
                'message' => $e->getError()
            ], 400);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 更新角色
     */
    public function update(Request $request)
    {
        try {
            $data = $request->param();
            $id = $data['id'];

            // 验证数据
            $validate = new RoleValidate();
            if (!$validate->scene('edit')->check($data)) {
                return json([
                    'code' => 400,
                    'message' => $validate->getError()
                ], 400);
            }

            $roleModel = new SystemRole();
            $role = $roleModel->find($id);

            if (!$role) {
                return json([
                    'code' => 400,
                    'message' => '角色不存在'
                ], 400);
            }

            $help = new Help();
            $data['system_user_id'] = $help->system_user();
            $flag = $roleModel->updateRole($id, $data);


            $help = new Help();
            $help->system_log($data, '修改角色');

            return json([
                'code' => 200,
                'message' => '更新成功',
                'data'=>$flag
            ]);

        } catch (ValidateException $e) {
            return json([
                'code' => 400,
                'message' => $e->getError()
            ], 400);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }


    /**
     * 更新角色
     */
    public function update2(Request $request)
    {
        try {
            $data = $request->param();
            $id = $data['id'];

            $roleModel = new SystemRole();
            $role = $roleModel->find($id);

            if (!$role) {
                return json([
                    'code' => 400,
                    'message' => '角色不存在'
                ], 400);
            }

            $flag = $roleModel->updateRole2($id, $data);


            $help = new Help();
            $help->system_log($data, '修改权限');

            return json([
                'code' => 200,
                'message' => '更新成功',
                'data'=>$flag
            ]);

        } catch (ValidateException $e) {
            return json([
                'code' => 400,
                'message' => $e->getError()
            ], 400);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }


    /**
     * 更新角色
     */
    public function update3(Request $request)
    {
        try {
            $data = $request->param();
            $id = $data['id'];
            $system_user_id = $data['system_user_id'];

            $roleModel = new SystemRole();
            $role = $roleModel->find($id);

            if (!$role) {
                return json([
                    'code' => 400,
                    'message' => '角色不存在'
                ], 400);
            }

            $flag = $roleModel->updateRole3($id,$system_user_id, $data);

            $help = new Help();
            $help->system_log($data, '修改权限');

            return json([
                'code' => 200,
                'message' => '更新成功',
                'data'=>$flag
            ]);

        } catch (ValidateException $e) {
            return json([
                'code' => 400,
                'message' => $e->getError()
            ], 400);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }


    /**
     * 删除角色
     */
    public function delete()
    {
        $id = input("id")??'';
        Db::startTrans();
        try {
            $roleModel = new SystemRole();
            $role = $roleModel->find($id);

            if (!$role) {
                return json([
                    'code' => 400,
                    'message' => '角色不存在'
                ], 400);
            }

            // 删除角色
            $role->delete();

            // 删除角色菜单关联
            Db::name('system_role_menus')->where('role_id', $id)->delete();

            $help = new Help();
            $help->system_log($id, '删除权限');

            Db::commit();

            return json([
                'code' => 200,
                'message' => '删除成功'
            ]);

        } catch (\Exception $e) {
            Db::rollback();
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量删除
     */
    public function batchDelete(Request $request)
    {
        Db::startTrans();
        try {
            $ids = $request->param('ids');
            if (empty($ids) || !is_array($ids)) {
                return json([
                    'code' => 400,
                    'message' => '参数错误'
                ], 400);
            }

            $roleModel = new SystemRole();

            // 删除角色
            $roleModel->whereIn('id', $ids)->delete();

            // 删除角色菜单关联
            Db::name('system_role_menus')->whereIn('role_id', $ids)->delete();

            $help = new Help();
            $help->system_log($ids, '删除权限');

            Db::commit();

            return json([
                'code' => 200,
                'message' => '删除成功'
            ]);

        } catch (\Exception $e) {
            Db::rollback();
            return json([
                'code' => 500,
                'message' => '服务器错误：' . $e->getMessage()
            ], 500);
        }
    }

    //租户列表
    public function tenant_list(){
        $list = Db::table("system_user")->field("id,truename")->where("role='tenant'")->select();
        return json([
            'code' => 200,
            'message' => 'success',
            'data' => $list
        ]);
    }
}